package com.utils.mapper;

import com.utils.Beans;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Mapper {
    private static final String KEY_CONCAT = "|";

    // 转换成按id键映射的对象
    public static <T> List<IDMapper<T>> idMappers(Collection<T> lists) {
        return lists.stream().map(v -> new IDMapper<T>(
                Long.parseLong(String.valueOf(Beans.maps(v).getOrDefault("id", 0L))),
                v
        )).filter(v -> v.id != 0L).collect(Collectors.toList());
    }

    // 转换成按key键映射的对象
    public static <T> List<KeyMapper<T>> keyMappers(Collection<T> lists, String... key) {
        return lists.stream().map(v -> new KeyMapper<T>(
                Stream.of(key).map(vv -> String.valueOf(Beans.maps(v).getOrDefault(vv, ""))).collect(Collectors.joining(KEY_CONCAT)),
                v
        )).filter(v -> !StringUtils.isEmpty(v)).collect(Collectors.toList());
    }

    // 转换成按key键映射的对象
    public static <T> List<KeyMapper<T>> keyMappers(Collection<T> lists, String key) {
        return lists.stream().map(v -> new KeyMapper<T>(
                String.valueOf(Beans.maps(v).getOrDefault(key, "")),
                v
        )).filter(v -> !StringUtils.isEmpty(v)).collect(Collectors.toList());
    }
}
